//
//  FootballMarchViewController.m
//  B
//
//  Created by lanou on 16/5/17.
//  Copyright © 2016年 裴启航. All rights reserved.
//

#import "FootballMarchViewController.h"
#import "FootBallMatchModel.h"
#import "SVProgressHUD.h"
#import "FootBallTableViewCell.h"
#import "TableViewCellFactory.h"
#import "SpreadCollectionView.h"
#import "FootballDetailViewController.h"

// 足球赛事 英超，西甲，德甲，意甲，法甲，中超
#define kFootBallMarchUrl @"http://api.avatardata.cn/Football/Query?key=fa9a9dfeed6b49968cc237676f82d076"

@interface FootballMarchViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
// 从collectionView中获取值
@property (nonatomic, strong) NSString *getCollectionTitle;
// 结束足球比赛数组
@property (nonatomic, strong) NSMutableArray *footballArray;
// 未开赛足球比赛数组
@property (nonatomic, strong) NSMutableArray *unStartFBArray;
@property (nonatomic, strong) SpreadCollectionView *spreadView;
@property (nonatomic, strong) UIButton *rightButton;

@end

@implementation FootballMarchViewController
-(UIButton *)rightButton
{
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightButton.frame = CGRectMake(0, 0, 20, 20);
        [_rightButton setImage:[UIImage imageNamed:@"list"] forState:UIControlStateNormal];
        [_rightButton addTarget:self action:@selector(rightClickAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

-(NSString *)getCollectionTitle
{
    if (!_getCollectionTitle) {
        _getCollectionTitle = [[NSString alloc]init];
    }
    return _getCollectionTitle;
}
-(NSMutableArray *)unStartFBArray
{
    if (!_unStartFBArray) {
        _unStartFBArray = [NSMutableArray array];
    }
    return _unStartFBArray;
}
-(NSMutableArray *)footballArray
{
    if (!_footballArray) {
        _footballArray = [NSMutableArray array];
    }
    return _footballArray;
}

-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - 通知
-(void)valuechangeString:(NSNotification *)text
{
    NSLog(@"%@",text.object);
    _getCollectionTitle = text.object;
    [self getFootBallMarchData];
    [SVProgressHUD showWithStatus:@"waiting"]; // 菊花创建
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor cyanColor];
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(valuechangeString:) name:@"tongzhi" object:nil];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 10000;
    [self.view addSubview:self.tableView];
    [self getFootBallMarchData];
    [self.tableView registerNib:[UINib nibWithNibName:@"FootBallTableViewCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([FootBallMatchModel class])];
}

-(void)rightClickAction:(UIButton *)button
{
    NSLog(@"jump");
    _spreadView = [[SpreadCollectionView alloc]init];
    self.delegate = _spreadView;
    if (button.selected == NO) {
        if (self.view.subviews.lastObject.frame.size.height <= ScreenHeight / 2) {
            [self.view.subviews.lastObject removeFromSuperview];
        } else {
            if ([self.delegate respondsToSelector:@selector(createCollectionView)]) {
                [self.delegate createCollectionView];
                _spreadView.alpha = 0.1;
                [self.view addSubview:_spreadView];
                [UIView animateWithDuration:0.3 animations:^{
                    self.view.subviews.lastObject.alpha = 1.0;
                }];
            }
        }
        button.selected = YES;
    } else {
        if (self.view.subviews.lastObject.frame.size.height > ScreenHeight / 2) {
            if ([self.delegate respondsToSelector:@selector(createCollectionView)]) {
                [self.delegate createCollectionView];
                _spreadView.alpha = 0.1;
                [self.view addSubview:_spreadView];
                [UIView animateWithDuration:0.3 animations:^{
                    self.view.subviews.lastObject.alpha = 1.0;
                }];
            }
        } else {
        [self.view.subviews.lastObject removeFromSuperview];
        }
        button.selected = NO;
    }
}

-(void)getFootBallMarchData
{
    if (_getCollectionTitle.length == 0) {
        _getCollectionTitle = @"英超";
    }
    NSString *fburl = [kFootBallMarchUrl stringByAppendingFormat:@"&league=%@", _getCollectionTitle];
    NSString *encodeUrl = [fburl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@", encodeUrl);
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:encodeUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        [SVProgressHUD setStatus:@"waiting"];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.footballArray = nil;
        NSDictionary *resultDict = responseObject[@"result"];
        NSDictionary *viewsDict = resultDict[@"views"];
        
        NSDictionary *saichengDic = viewsDict[@"saicheng1"];
        NSLog(@"%@", saichengDic);
        
        for (NSDictionary *saicheng in saichengDic) {
            [self.footballArray addObject:[FootBallMatchModel modelWithDic:saicheng]];
        }
        
        NSDictionary *unStartSaichengDic = viewsDict[@"saicheng2"];
        NSLog(@"%@", unStartSaichengDic);
        for (NSDictionary *unStart in unStartSaichengDic) {
            [self.unStartFBArray addObject:[FootBallMatchModel modelWithDic:unStart]];
        }
        [self.tableView reloadData];
        [SVProgressHUD dismiss]; // 菊花消失
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"football ++ %@", error);
    }];
}



#pragma mark - 代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.footballArray.count;
    } else {
        return self.unStartFBArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FootBallMatchModel *model = [[FootBallMatchModel alloc]init];
    if (indexPath.section == 0) {
        model = self.footballArray[indexPath.row];
        BaseTableViewCell *cell = [TableViewCellFactory cellWithModelClass:[model class] tableView:tableView index:indexPath];
        [cell setDataWithModel:model];
        return cell;
        
    } else {
        model = self.unStartFBArray[indexPath.row];
        BaseTableViewCell *cell = [TableViewCellFactory cellWithModelClass:[model class] tableView:tableView index:indexPath];
        [cell setDataWithModel:model];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FootBallMatchModel *footballModel = [[FootBallMatchModel alloc]init];
    FootballDetailViewController *fbVC = [[FootballDetailViewController alloc]init];
    if (indexPath.section == 0) {
        footballModel = self.footballArray[indexPath.row];
        fbVC.getUrl1 = footballModel.c52Link;
    } else {
        footballModel = self.unStartFBArray[indexPath.row];
        fbVC.getUrl1 = footballModel.c52Link;
    }
    [self.navigationController pushViewController:fbVC animated:YES];
}
// 分区顶部视图
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
        if (section == 0) {
            NSString *zifuchuang = @" - 第一轮";
            // 球赛名称 - 结束
            NSString *finishTeam = [_getCollectionTitle stringByAppendingString:zifuchuang];
            
            NSLog(@"%@", finishTeam);
            return finishTeam;
        } else {
            NSString *zifuchuang = @" - 第二轮";
            NSString *str = [_getCollectionTitle stringByAppendingString:zifuchuang];
            return str;
        }
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return @[@"第一轮",@"第二轮"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
